package com.comecrd.controller;

import com.comecrd.model.CheckIn;
import com.comecrd.model.Image;
import com.comecrd.model.dto.CheckInDTO;
import com.comecrd.model.dto.ImageDTO;
import com.comecrd.service.CheckInService;
import com.comecrd.service.UserService;
import com.comecrd.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/api/checkin")
public class CheckInController {
    
    @Autowired
    private CheckInService checkInService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JWTUtil jwtUtil;
    
    @Value("${image.upload.path}")
    private String imageUploadPath;
    
    @Value("${image.base.url}")
    private String imageBaseUrl;
    
    // 发布打卡
    @PostMapping("/publish")
    public ResponseEntity<Map<String, Object>> publishCheckIn(
            @RequestHeader("Authorization") String token,
            @RequestParam("content") String content,
            @RequestParam("locationName") String locationName,
            @RequestParam("latitude") Double latitude,
            @RequestParam("longitude") Double longitude,
            @RequestParam(value = "images", required = false) MultipartFile[] images) throws IOException {
        
        // 从token中获取openId
        String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
        
        // 查找用户
        com.comecrd.model.User user = userService.findByOpenId(openId);
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 创建打卡记录
        CheckIn checkIn = new CheckIn();
        // 使用userId替代user对象
        checkIn.setUserId(user.getId());
        checkIn.setContent(content);
        checkIn.setLocationName(locationName);
        checkIn.setLatitude(latitude);
        checkIn.setLongitude(longitude);
        
        // 处理图片上传
        List<String> imageUrls = new ArrayList<>();
        if (images != null && images.length > 0) {
            for (int i = 0; i < images.length; i++) {
                MultipartFile file = images[i];
                if (!file.isEmpty()) {
                    // 生成文件名
                    String fileName = UUID.randomUUID().toString() + ".jpg";
                    String filePath = imageUploadPath + File.separator + fileName;
                    
                    // 确保目录存在
                    File uploadDir = new File(imageUploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }
                    
                    // 保存文件
                    file.transferTo(new File(filePath));
                    
                    // 收集图片URL
                    imageUrls.add(imageBaseUrl + fileName);
                }
            }
        }
        checkIn.setImageUrls(imageUrls);
        
        // 保存打卡记录
        checkIn = checkInService.saveCheckIn(checkIn);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("checkIn", checkInService.convertToDTO(checkIn, user.getId()));
        
        return ResponseEntity.ok(response);
    }
    
    // 获取打卡列表
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getCheckInList(
            @RequestHeader(value = "Authorization", required = false) String token,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        // 获取当前用户ID
        Long currentUserId = null;
        if (token != null) {
            try {
                String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
                com.comecrd.model.User user = userService.findByOpenId(openId);
                if (user != null) {
                    currentUserId = user.getId();
                }
            } catch (Exception e) {
                // token无效，忽略
            }
        }
        
        // 查询打卡列表
        List<CheckInDTO> checkInDTOs = checkInService.findAll(currentUserId, page + 1, size);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("list", checkInDTOs);
        response.put("page", page);
        response.put("size", size);
        
        return ResponseEntity.ok(response);
    }
    
    // 获取用户的打卡列表
    @GetMapping("/user/list")
    public ResponseEntity<Map<String, Object>> getUserCheckInList(
            @RequestParam Long userId,
            @RequestHeader(value = "Authorization", required = false) String token,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        // 获取当前用户ID
        Long currentUserId = null;
        if (token != null) {
            try {
                String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
                com.comecrd.model.User user = userService.findByOpenId(openId);
                if (user != null) {
                    currentUserId = user.getId();
                }
            } catch (Exception e) {
                // token无效，忽略
            }
        }
        
        // 查询用户打卡列表
        List<CheckInDTO> checkInDTOs = checkInService.findByUserId(userId, currentUserId, page + 1, size);
        
        // 获取用户统计信息
        CheckInService.UserStats stats = checkInService.getUserStats(userId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("list", checkInDTOs);
        response.put("page", page);
        response.put("size", size);
        response.put("stats", stats);
        
        return ResponseEntity.ok(response);
    }
    
    // 获取打卡详情
    @GetMapping("/detail/{id}")
    public ResponseEntity<Map<String, Object>> getCheckInDetail(
            @PathVariable Long id,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        // 获取当前用户ID
        Long currentUserId = null;
        if (token != null) {
            try {
                String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
                com.comecrd.model.User user = userService.findByOpenId(openId);
                if (user != null) {
                    currentUserId = user.getId();
                }
            } catch (Exception e) {
                // token无效，忽略
            }
        }
        
        // 查询打卡详情
        CheckInDTO checkInDTO = checkInService.findById(id, currentUserId);
        if (checkInDTO == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "打卡记录不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("checkIn", checkInDTO);
        
        return ResponseEntity.ok(response);
    }
    
    // 删除打卡
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Map<String, Object>> deleteCheckIn(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {
        
        // 从token中获取openId
        String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
        
        // 查找用户
        com.comecrd.model.User user = userService.findByOpenId(openId);
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 查找打卡详情（用于验证所有权）
        CheckInDTO checkInDTO = checkInService.findById(id, user.getId());
        if (checkInDTO == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "打卡记录不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 验证是否是用户自己的打卡记录
        if (!checkInDTO.getUser().getId().equals(user.getId())) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "无权删除此打卡记录");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 删除打卡记录
        checkInService.deleteById(id);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        
        return ResponseEntity.ok(response);
    }
}